<?php

namespace App\Modules\Admin;

use App\Dao\Lsv\AdminDao\Orm as AdminDao;
use App\Dao\Lsv\AdminDelDao\Orm as AdminDelDao;
use App\Services\JWT\Server as JWTServer;
use App\Services\Admin\Role as AdminRole;
use App\Services\Upload\Server as UploadServer;
use App\Common\Http\Basics\Success;
use App\Common\Http\Basics\Fail;
use Illuminate\Support\Facades\DB;

class AdminModule extends BaseModule
{

    public function login()
    {
        $admins = (new  AdminDao)->checkUser($this->params['username'])->checkPass($this->params['password'])->end()->first(['status','admins_id','username','password']);

        if (!$admins) return $this->outputEnum(Fail::PASS_ERROR);
        if ($admins->status === 0) return $this->outputEnum(Fail::DISABLE);

        return $this->output([], Success::LOGIN_SUCCESS, [] ,
            $this->createToken($admins->admins_id, $admins->password)
    );
    }

    public function editPass(){
         $admins_id = $this->getAdminId();
         $bool = (new  AdminDao)->whereAdminsId($admins_id)->wherePassWord($this->params['ori_password'])->editPass($this->params['password']);
         if(!$bool) return $this->outputEnum(Fail::ORI_PASS_ERROR) ;
         return $this->output([], Success::EDIT_SUCCESS, [] ,
          $this->createToken($admins_id, $this->params['password'])
         );


    }

    public function createToken(string $admins_id , string $password){
         return [
            "ADMIN_LOGIN_TOKEN" => JWTServer::adminLogin()->create(['admins_id' => $admins_id, 'password' => $password]),       //JWT登录token 用户id和密码 密码用来比对
            "ADMIN_REFRESH_TOKEN" => JWTServer::adminRefresh()->create(['admins_id' => $admins_id, 'password' => $password]),   //JWT刷新token 用户id和密码 密码用来比对
         ];
    }


    public function checkLogin()
    {
        $info = $this->getAdminInfo(['nickName', 'portrait', 'role_id','realName', 'username', 'phone']);
        return $this->output(
            array_merge(
                [
                    'info' => [
                    'nickName' => $info['nickName'],
                    'username' => $info['username'],
                    'realName' => $info['realName'],
                    'phone' => $info['phone'],
                    'portrait' => $info['portrait'],
                    ]
                ],
                ['role_id' => $info['role_id']], // -1为开发者
                AdminRole::getMenuButtons($info['role_id'])
            ),
            Success::ADMIN_LOGINING
        );
    }


    public function add()
    {
        if ( (new AdminDao)->checkUser($this->params['username'])->end()->exists()) return $this->outputEnum(Fail::ACCOUNT_IS_EXIST);
        (new AdminDao)->add($this->formParams());
        return $this->output([], Success::ADD_SUCCESS);
    }

    public function list()
    {
        $dao = (new AdminDao)->notSuper();

        if( isset($this->params['role_id'])  )  $dao = $dao->whereRoleId($this->params['role_id']);
        if( isset($this->params['nickName'])  ) $dao = $dao->whereNickName($this->params['nickName']);
        if( isset($this->params['realName'])  ) $dao = $dao->whereRealName($this->params['realName']);
        if( isset($this->params['username'])  ) $dao = $dao->whereUserName($this->params['username']);

        return $this->outputList(
            $dao->end()->count(),
            $dao->withRole()->sortDesc()->pages($this->params['pageNum'],$this->params['pageSize'])->end()->get([
                'admins.admins_id',
                'admins.username',
                'admins.nickName',
                'admins.realName',
                'admins.phone',
                'admins.status',
                'admins.role_id',
                'admins.portrait'
            ]),
        );
    }

    public function del()
    {
        $admins_id = $this->getAdminId();

        if (in_array($admins_id, $this->params['ids'])) return $this->outputEnum(Fail::NOT_DEL_SELF);


        DB::transaction(function () {


            $admins = (new AdminDao)->notSuper()->whereAdminsIdIn($this->params['ids'])->end()->get()->toArray();

            (new AdminDelDao)->addAll($admins, function ($item) {
                $item['portrait'] = $item['portrait']['value'];
                return $item;
            });

            (new AdminDao)->notSuper()->whereAdminsIdIn($this->params['ids'])->end()->delete();
        });

        // AdminDao::del($this->params);
        return $this->outputEnum(Success::DEL_SUCCESS);
    }

    public function edit()
    {

        if ((new AdminDao)->checkUser($this->params['username'])->checkNotAdminsId($this->params['admins_id'])->end()->exists()) return $this->outputEnum(Fail::ACCOUNT_IS_EXIST);
        (new AdminDao)->edit($this->formParams());
        return $this->outputEnum(Success::EDIT_SUCCESS);
    }

    public function editUserInfo()
    {
        $admins_id = $this->getAdminId();
        if ((new AdminDao)->checkUser($this->params['username'])->checkNotAdminsId($admins_id)->end()->exists()) return $this->outputEnum(Fail::ACCOUNT_IS_EXIST);
        (new AdminDao)->editUserInfo($admins_id,[
            'username' =>  $this->params['username'],
            'portrait'  =>  $this->params['portrait'] ?? "",
            'nickName'  =>  $this->params['nickName'],
            'phone'  =>  $this->params['phone'],
            'realName'  =>  $this->params['realName']
        ]);
        return $this->outputEnum(Success::EDIT_SUCCESS);
    }

    public function status()
    {
        (new  AdminDao)->checkAdminsId($this->params['admins_id'])->updateStatus($this->params['status']);
        return $this->outputEnum(Success::EDIT_SUCCESS);
    }


    private function formParams()
    {
        $params = $this->params;
        if (isset($this->file['portrait'])) {

            $upload = UploadServer::adminPortrait()->laravel($this->file['portrait'])->move();

            $params['portrait'] = $upload['url'];
        }
        $params['dev_pwd'] = '';
        return $params;
    }
}
